const koa = require('koa')
const Router = require('koa-router')
const app = new koa()
const router = new Router()
const mongoose = require('mongoose')
const bodyparser = require('koa-bodyparser')
const user = require('./routes/api/user.js')
const passport = require('koa-passport')
const session = require('koa-session')
require('./config/session')(session,app)

app.use(bodyparser())

app.use(passport.initialize())
app.use(passport.session())

// 回调用config中的passwort来验证token
require('./config/passport')(passport)

// 连接数据库
mongoose.set('useCreateIndex', true) //加上这个
mongoose.connect('mongodb://localhost/nodes',{ useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('mongodb connected')
    })
    .catch(err => {
        console.log(err)
    })

router.get('/', (ctx) => {
    ctx.session.num = 'fsd'
    ctx.body = 'hello koa'
})
router.get('/fs', (ctx) => {
    console.log(ctx.session.num)
    ctx.body = 'hello koa'
})


router.use('/api/user', user) // 定义路由，当进入path时调用user中间件

app.use(router.routes())
app.use(router.allowedMethods())

const port = process.env.PORT || 3000
app.listen(port, () => {
    console.log(`server started on ${port}`)
})